package com.bawei.module_live.ui.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.recyclerview.widget.RecyclerView
import com.bawei.lib_common.dp
import com.bawei.module_live.data.OrderHotData
import com.bawei.module_live.databinding.ItemOrderHotBinding
import com.bawei.module_live.databinding.ItemOrderHotTop3Binding
import com.bawei.module_live.databinding.ItemOrderHotTop3RowBinding

class OrderHotAdapter(
    private val data: MutableList<OrderHotData>,
    private val useTop3Special: Boolean = true,
    private val isDaihuoRanking: Boolean = false
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    var onItemClick: ((OrderHotData) -> Unit)? = null
    private val followStatusMap = mutableMapOf<Int, Boolean>() // key: id, value: isFollowed

    companion object {
        private const val TYPE_TOP3_ROW = 1
        private const val TYPE_NORMAL = 2
    }

    override fun getItemViewType(position: Int): Int {
        return if (useTop3Special && position == 0) TYPE_TOP3_ROW else TYPE_NORMAL
    }

    override fun getItemCount(): Int {
        return if (useTop3Special) {
            if (data.size > 3) 1 + (data.size - 3) else 1
        } else {
            data.size
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == TYPE_TOP3_ROW) {
            val binding = ItemOrderHotTop3RowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            Top3RowViewHolder(binding)
        } else {
            val binding = ItemOrderHotBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            NormalViewHolder(binding)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (data.isEmpty()) return
        if (useTop3Special && position == 0) {
            (holder as Top3RowViewHolder).bind(data.take(3))
        } else {
            val realIndex = position + 2
            Log.d("OrderHotAdapter", "onBindViewHolder: position=$position, realIndex=$realIndex, data.size=${data.size}")
            if (realIndex < data.size) {
                val item = data[realIndex]
                val rank = realIndex + 1
                (holder as NormalViewHolder).bind(item, rank)
            }
        }
    }

    fun updateData(newList: List<OrderHotData>) {
        data.clear()
        data.addAll(newList.map { it.copy() })
        notifyDataSetChanged()
    }

    private fun handleFollowClick(item: OrderHotData, button: Button, adapterPosition: Int? = null) {
        val itemId = item.id ?: return
        val currentFollowStatus = followStatusMap[itemId] ?: false
        val newFollowStatus = !currentFollowStatus
        followStatusMap[itemId] = newFollowStatus
        button.text = if (newFollowStatus) "已关注" else "关注"
        val currentHot = item.hot ?: 0
        val newHot = if (newFollowStatus) currentHot + 1 else currentHot - 1
        item.hot = newHot
        if (adapterPosition != null && adapterPosition != RecyclerView.NO_POSITION) {
            notifyItemChanged(adapterPosition)
        } else {
            notifyItemChanged(getAdapterPositionById(itemId))
        }
    }

    private fun getAdapterPositionById(itemId: Int): Int {
        if (useTop3Special) {
            for (i in 3 until data.size) {
                if (data[i].id == itemId) {
                    return i - 2
                }
            }
        } else {
            for (i in data.indices) {
                if (data[i].id == itemId) {
                    return i
                }
            }
        }
        return RecyclerView.NO_POSITION
    }

    inner class Top3RowViewHolder(val binding: ItemOrderHotTop3RowBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(top3: List<OrderHotData>) {
            val card1 = binding.root.findViewById<View>(com.bawei.module_live.R.id.card1)
            val card2 = binding.root.findViewById<View>(com.bawei.module_live.R.id.card2)
            val card3 = binding.root.findViewById<View>(com.bawei.module_live.R.id.card3)
            val cardBindings = listOf(
                ItemOrderHotTop3Binding.bind(card1),
                ItemOrderHotTop3Binding.bind(card2),
                ItemOrderHotTop3Binding.bind(card3)
            )
            val avatarSize = 52.dp
            for (i in 0..2) {
                val cardBinding = cardBindings[i]
                if (i < top3.size) {
                    val item = top3[i]
                    cardBinding.tvRank.text = (i + 1).toString()
                    cardBinding.tvNickname.text = item.room_name ?: ""
                    val params = cardBinding.ivAvatar.layoutParams
                    params.width = avatarSize
                    params.height = avatarSize
                    cardBinding.ivAvatar.layoutParams = params
                    cardBinding.root.visibility = View.VISIBLE
                    val itemId = item.id
                    val isFollowed = itemId?.let { followStatusMap[it] } ?: false
                    cardBinding.btnFollow.text = if (isFollowed) "已关注" else "关注"
                    cardBinding.btnFollow.setOnClickListener {
                        if (itemId != null) {
                            val currentFollowStatus = followStatusMap[itemId] ?: false
                            val newFollowStatus = !currentFollowStatus
                            followStatusMap[itemId] = newFollowStatus
                            cardBinding.btnFollow.text = if (newFollowStatus) "已关注" else "关注"
                            val currentHot = item.hot ?: 0
                            val newHot = if (newFollowStatus) currentHot + 1 else currentHot - 1
                            item.hot = newHot
                            notifyDataSetChanged()
                        }
                    }
                    cardBinding.root.setOnClickListener {
                        onItemClick?.invoke(item)
                    }
                } else {
                    cardBinding.root.visibility = View.INVISIBLE
                    cardBinding.root.setOnClickListener(null)
                }
            }
        }
    }

    inner class NormalViewHolder(val binding: ItemOrderHotBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: OrderHotData, rank: Int) {
            binding.tvRank.text = rank.toString()
            binding.tvNickname.text = item.room_name ?: ""
            binding.tvScore.text = "${item.hot} 热度"
            val itemId = item.id
            val isFollowed = itemId?.let { followStatusMap[it] } ?: false
            binding.btnFollow.text = if (isFollowed) "已关注" else "关注"
            binding.btnFollow.setOnClickListener {
                handleFollowClick(item, binding.btnFollow, bindingAdapterPosition)
            }
            binding.root.setOnClickListener {
                onItemClick?.invoke(item)
            }
        }
    }
}